package com.dingup.mock.module;

import com.dingup.mock.bean.home.SystemData;
import com.dingup.util.GDateUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import static com.dingup.mock.util.ConstUtil.CACHE_AUTO_CLEAR_EXPIRED_SECOND;


/**
 * 系统常用数据缓存
 * 比如:首页套题列表数据等
 * Created by yanggavin on 16/6/7.
 */
public class SSystemDataCache {
    private static class LazyHolder {
        private static final SSystemDataCache INSTANCE = new SSystemDataCache();
    }
    public static SSystemDataCache getInstance() {
        return SSystemDataCache.LazyHolder.INSTANCE;
    }
    private SSystemDataCache() { }

    /**
     * 系统常用数据
     */
    private final ConcurrentMap<String, SystemData> sysDataMapInfoMap = new ConcurrentHashMap<>();


    /**
     * 添加缓存
     * @param key
     * @param sd
     */
    public void put(String key, SystemData sd){
        // 阅读题型的真题演练每天都更新题库, 暂时去掉阅读题型的缓存;
        if (!sysDataMapInfoMap.containsKey(key) && !key.equalsIgnoreCase("reading")){
            sysDataMapInfoMap.put(key, sd);
        }
        // 清理超时的缓存数据
        clearExpiredData();
    }

    /**
     * 提取缓存
     * @param key
     * @return
     */
    public SystemData get(String key){
        if (sysDataMapInfoMap.containsKey(key)){
            return sysDataMapInfoMap.get(key);
        }
        return null;
    }

    /**
     * 清空全部内容
     */
    public void clear(){
        sysDataMapInfoMap.clear();
    }

    /**
     * 清理过期数据
     */
    private void clearExpiredData(){
        List<String> expiredList = new ArrayList<>();
        Iterator iterator = sysDataMapInfoMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, SystemData> entry = (Map.Entry<String, SystemData>)iterator.next();
            if (GDateUtil.checkExpired(entry.getValue().getBeginTime(), CACHE_AUTO_CLEAR_EXPIRED_SECOND)){
                expiredList.add(entry.getKey());
            }
        }
        // 清理超时的缓存数据
        for (String id : expiredList){
            sysDataMapInfoMap.remove(id);
        }
    }
}
